// cloudfunctions/getPointsRecords/index.js
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    const { userId, pageSize = 10, pageNum = 1, type } = event
    
    if (!userId) {
      return { success: false, message: '用户ID不能为空' }
    }
    
    // 构建查询条件
    let query = db.collection('user_points')
      .where({ userId: userId })
    
    // 执行查询
    const res = await query.get()
    
    // 如果用户没有积分记录
    if (!res.data || res.data.length === 0) {
      return { success: true, records: [] }
    }
    
    // 获取积分记录
    let records = res.data[0].records || []
    
    // 根据类型筛选
    if (type === 1 || type === 2 || type === 3) {
      records = records.filter(record => record.type === type)
    }
    
    // 按时间倒序排序
    records = records.sort((a, b) => {
      return new Date(b.createTime) - new Date(a.createTime)
    })
    
    // 分页处理
    const startIndex = (pageNum - 1) * pageSize
    const endIndex = pageNum * pageSize
    const paginatedRecords = records.slice(startIndex, endIndex)
    
    return {
      success: true,
      records: paginatedRecords
    }
    
  } catch (error) {
    console.error('获取积分记录失败:', error)
    return { success: false, message: '获取积分记录失败' }
  }
}